<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/11/9  19:27
 */
namespace app\api\logic;
use app\api\BaseModel;
use app\api\controller\Msn;
use think\Cache;
use think\Db;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WXorder;
use EasyWeChat\Payment\Merchant as Merchantr;
class Pay extends  BaseModel{

    /**
     * app
     */
    public function app()
    {
        $options = [
            'app_id' => config("wx.app_id"),
            'secret' => config('wx.app_secret'),
            'token'  => config('wx.token'),
            'log' => [
                'level'      => 'debug',
                'permission' => 0777,
                'file'       => '/tmp/easywechat.log',
            ],

            // ...
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => 'http://qch.gzldrj.com/wap/wechat/oauthCallback',
            ],
            'payment' => [
                'merchant_id'        =>config("wx.mch_id"),
                'key'                =>  config("wx.key"),
                'cert_path'          =>EXTEND_PATH. 'cert\apiclient_cert.pem', // XXX: 绝对路径！！！！
                'key_path'           => EXTEND_PATH.'cert\apiclient_key.pem',      // XXX: 绝对路径！！！！
                'notify_url'       => request()->domain().'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            ],
        ];
        return  new Application($options);
    }
    /**
     * 收银台
     */
    public function cashier()
    {

        $db_order = db('order');
        $where['delete']=0;
        $where['id']=$this->requestData['id'];
        $where['uid']=$this->user['id'];
        $list=$db_order->where($where)->find();
        if(!$list) return array('message'=>'订单不存在');
        $list['countdown']=$list['create_time']+30*60-NOW_TIME;
        if( $list['countdown']<=0){
            $db_order->where($where)->update(array("status"=>-1));
            $list['status']=-1;
        }
        //if($list['status']==-1) return array('message'=>'订单已关闭，请重新下单');
        $list['num']=($list['end_time']-$list['start_time'])/(24*60*60);
        if($list['realname']){
            $list['realname']=unserialize($list['realname']);
        }
        $list['image']=IMG_PATH. $list['image'];

        $list['create_time']=date("Y-m-d H:i:s",$list['create_time']);
        $list['finish_time']=!empty($list['finish_time'])?date("Y-m-d H:i:s",$list['finish_time']):$list['finish_time'];
        $list['start_time']=date("Y-m-d",$list['start_time']);
        $list['end_time']=date("Y-m-d",$list['end_time']);
        $app=$this->app();
        $payment = $app->payment;

        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => '七彩虹酒店',
            'detail'           => $list['title'],
            'out_trade_no'     =>  $list['order_sn'],
            'total_fee'        => $list['price']*100, // 单位：分
            'notify_url'       => request()->domain().'/api/pay/notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->user['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new WXorder($attributes);
        $result = $payment->prepare($order);
        if ($result->return_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $json = $payment->configForPayment($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false
            return array("detail"=>$list,'jsapi'=>$json);
        }elseif($result->return_code == 'FAIL'){
            return array("message"=>$result->return_msg);
        }
    }

    public function pay()
    {
        $wx['out_trade_no']='201712191350305028';
        $log=db("order")->where("order_sn=".$wx['out_trade_no'])->find();
        $member=db("member")->where("id=".$log['uid'])->find();
        $app=$this->app();
        $data = array(
            'touser' => $member['openid'],
            'template_id' => 'hokLEPoMZbdAwyVrSzPJP95wdGeXxQfIh7jDIF8WvTQ',
            'url' => request()->domain() . '/qchwap/#/orderDetail?id='.$log['id'],
            'data' => [
                'first' => '购票成功通知',
                'keyword1' => '七彩虹酒店',
                'keyword2' => $log['title'],
                'keyword3' =>  $log['price'],
                'remark' => '如有疑问请致电酒店：0766-6636678'
            ]
        );
        $app->notice->send($data);

    }
    /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }
        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }
    public function notify(){
        $xml = file_get_contents('php://input');
/*        $xml='<xml><appid><![CDATA[wxe708d15eb70ba886]]></appid>
<bank_type><![CDATA[CFT]]></bank_type>
<cash_fee><![CDATA[270]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[Y]]></is_subscribe>
<mch_id><![CDATA[1492502302]]></mch_id>
<nonce_str><![CDATA[5a3a0bb4be416]]></nonce_str>
<openid><![CDATA[ofFVE0wdFu_TSu0BXziutsWJMjgI]]></openid>
<out_trade_no><![CDATA[201712201505243799]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[247C6138269728917D5F0A948952DD6E]]></sign>
<time_end><![CDATA[20171220150535]]></time_end>
<total_fee>270</total_fee>
<trade_type><![CDATA[JSAPI]]></trade_type>
<transaction_id><![CDATA[4200000025201712207705209894]]></transaction_id>
</xml>';*/
        if(!$xml){
            exit('非法访问');
        }
        $path=ROOT_PATH . 'public' . DS .'static' . DS  . 'log' . DS  .date('Ymd') ;
        if (false !== $this->checkPath($path)) {
            $paths=$path.'/'.'log.txt';
            file_put_contents($paths,$xml,FILE_APPEND);
        }
        $wx=$this->xmlToArray($xml);
        ksort($wx);// 对数据进行排序
        $str =$this-> ToUrlParams($wx);//对数据拼接成字符串
        $user_sign = strtoupper(md5($str));
        if($user_sign == $wx['sign']){//验证成功
            $log=db("order")->where("order_sn=".$wx['out_trade_no'])->find();

            if(!empty($log) && $log['status'] == '0' && (($wx['total_fee'] / 100) == $log['price'])) {//订单存在并且没支付状态，金额一致
                Db::startTrans();
                try{
                    $res=db("order")->where("order_sn=".$wx['out_trade_no'])->update(array("status"=>1,'pay_time'=>NOW_TIME));
                    $data=array(
                        'title'=>'订单号：'.$wx['out_trade_no'],
                        'image'=>$log['image'],
                        'des'=>'订单已支付，快去使用吧',
                        'uid'=>$log['uid'],
                        'create_time'=>NOW_TIME,
                        'relation_id'=>$log['id'],
                    );
                    $add=db("tip_user")->insert($data);
                    if($log['type']==0){
                        $member=db("member")->where("id=".$log['uid'])->find();
                        $app=$this->app();
                        $real=unserialize($log['realname']);
                        $realname='';
                        foreach($real as $ddd){
                            $realname.=$ddd.',';
                        }
                        $realname=substr($realname,0,-1);
                        $data=array(
                            'touser' => $member['openid'],
                            'template_id' => 'xsRnKBY78P5agKgIXDuw1BARKaWgV35_dZLbiAB2nmo',//'YioEzkodB3qhmrqEgk_OkdzEobfdXMrz81cLA8vmbCI',
                            'url' =>  request()->domain().'/qchwap/#/orderDetail?id='.$log['id'],
                            'data' => [
                                'first' => '您好，您已成功预订成功！',
                                'order' => $log['order_sn'],
                                'Name'=>$realname,
                                'datein' => date("Y-m-d",$log['start_time']),
                                'dateout' => date("Y-m-d",$log['end_time']),
                                'number'=>$log['count'],
                                'room type'=>$log['title'],
                                'pay'=>'￥'.number_format($log['price'],2),
                                'remark' => '如有疑问请致电酒店：0766-6636678'
                            ]
                        );
                        $app->notice->send($data);
                        if($log['mobile']){
                            $response = (new Msn())->sendSms(
                                "新兴县七彩虹酒店", // 短信签名
                                'SMS_117512246', // 短信模板编号
                                $log['mobile'], // 短信接收者
                                Array(  // 短信模板中字段的值
                                    "ordersn"=>$log['order_sn'],
                                    "start"=>date("Y-m-d",$log['start_time']),
                                    "room"=>$log['title'],
                                    "count"=>$log['count'],
                                    "sum"=>($log['end_time']-$log['start_time'])/(24*60*60),
                                    "price"=>$log['price'],
                                ),
                                "123"
                            );
                        }

                    }else{
                        $member=db("member")->where("id=".$log['uid'])->find();
                        $app=$this->app();

                        $data = array(
                            'touser' => $member['openid'],
                            'template_id' => 'hokLEPoMZbdAwyVrSzPJP95wdGeXxQfIh7jDIF8WvTQ',
                            'url' => request()->domain() . '/qchwap/#/orderDetail?id='.$log['id'],
                            'data' => [
                                'first' => '购票成功通知',
                                'keyword1' => $log['order_sn'],
                                'keyword2' => $log['title'],
                                'keyword3' => '￥'.number_format($log['price'],2),
                                'remark' => '如有疑问请致电酒店：0766-6636678'
                            ]
                        );
                        $app->notice->send($data);
                    }
                    $new_order = Cache::get("new_order");
                    $new_order = json_decode($new_order);
                    $new_order[] =$log['id'];
                    Cache::set("new_order", json_encode($new_order), 864000);
                    Db::commit();
                } catch (\Exception $e) {// 回滚事务
                    Db::rollback();
                    echo   $e->getMessage();
                    exit('fail');
                }
                if($log['cart_id'] || $log['code']){
                    (new Coupon())->deletecoupon($log['code'],$log['cart_id']);
                }
                if( $res) {
                    exit('success');
                }else{
                    exit('fail');
                }
            }
            exit('fail');
        }
        exit('fail');
    }
    public  function xmlToArray($xml)
    {

        //禁止引用外部xml实体

        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }
    /**
     * 格式化参数格式化成url参数
     */
    private function ToUrlParams($arr)
    {
        $weipay_key = config("wx.key");//微信的key,这个是微信支付给你的key，不要瞎填。
        $buff = "";
        foreach ($arr as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff.'&key='.$weipay_key;
    }

}